using System;
using UnityEngine;
using UnityEngine.UI;
#if Supersonic
using SupersonicWisdomSDK;
#endif
/// <summary>
/// main UI
/// </summary>
public class MBattleMainUI : BattleMainUI, IMBattleController
{
    public SpriteNum gameTimeText;
    public JoyPad joyPad;

    public BattleAttackBtn battleAttackBtn;
    public Text uguiText;

    //public FeverProgressUI feverProgressUI;

    public NumShowToast addNumToast;
    public NumShowToast minusNumToast;

    public GameObject levelListObj;

    public Transform coinIconPos;

    public GameObject chatBtn;
    
    private MBattleSceneController battleSceneController => GetComponentInParent<MBattleSceneController>();
    public MBattleController MBattleController => battleController as MBattleController;

    MBattleUIWidgetInfoCtrl mBattleUiWidgetInfoCtrl => this.m_BattleWidgetInfoController as MBattleUIWidgetInfoCtrl;

    public GameObject homeSceneObj;
    public GameObject runnerSceneObj;

    private IMBattleUI m_MainUIListener;
    public override IBattleMainUI uiListener
    {
        get => m_MainUIListener;
        set => m_MainUIListener = value as IMBattleUI;
    }

    public override void Awake()
    {
        base.Awake();

        if (battleAttackBtn)
        {
            battleAttackBtn.onClick = OnClickAttack;
            battleAttackBtn.gameObject.SetActive(false);
        }

        if (finger)
        {
#if DEBUG
            finger.SetActive(true);
#else
                finger.SetActive(false);
#endif
        }

        if (uguiText)
        {
#if !RELEASE
            uguiText.gameObject.SetActive(true);
#else
            uguiText.gameObject.SetActive(false);
            levelListObj.SetActive(false);
#endif
        }
    }


    public override void Init(BattleController mController)
    {
        base.Init(mController);

        if (gameTimeText)
        {
            if (mController.limitTime > 0)
                gameTimeText.num = mController.limitTime;
            else
                gameTimeText.gameObject.SetActive(false);
        }

        /*if (feverProgressUI)
            feverProgressUI.Init(mController as MBattleController);*/

        if(addNumToast)
            addNumToast.gameObject.SetActive(false);
        if (minusNumToast)
            minusNumToast.gameObject.SetActive(false);
        
        //chatBtn.SetActive(MGame.instance.MUser.chats.Count > 0);

        if (MBattleController.homeScene)
        {
            homeSceneObj.SetActive(true);
            runnerSceneObj.SetActive(false);
            
            this.OnClickStart();
        }
        else
        {
            homeSceneObj.SetActive(false);
            runnerSceneObj.SetActive(true);
        }
    }

    public override void Start()
    {
        base.Start();

        joyPad.onMove = OnMove;
        joyPad.onStop = OnStop;
        joyPad.onStay = OnStay;
    }

    public override void OnClickStart()
    {
        battleController.GameStart();

        this.ShowBattle();
        
        //this.joyPad.gameObject.SetActive(false);
        //GetComponentInParent<BattleSceneViewController>().PlayBattleMusic();
    }

    #region click

    private void OnMove(Vector2 vec)
    {
        //Debug.Log($"OnMove:{vec}  this.battleController.GameStarted:{this.battleController.GameStarted}");
        if (!this.battleController.GameStarted)
        {
            this.OnClickStart();
        }
        m_MainUIListener?.OnOptMove(vec);
    }
    private void OnStay(Vector2 pos)
    {
        //Debug.Log($"OnMove:{vec}");
        m_MainUIListener?.OnOptStay(pos);
    }

    private void OnStop(Vector2 vec)
    {
        //GameDebug.LogError("BattleUI OnStop");

        m_MainUIListener?.OnOptStop();
    }

    public void OnClickSkill()
    {
        m_MainUIListener?.OnOptSkill();
    }

    public void OnClickAttack()
    {
        m_MainUIListener?.OnOptAttack();
    } 
    
    public void OnClickShop()
    {
        GameDebug.LogError($"show shop");

        var skins = this.m_Controller.parentNav.LoadDisplay<SkinsListViewController>();

        SkinsListVCData skinsListVCData = SkinsListViewController.GetSkinsListVCData(MGame.instance.MUser);//battleSceneController.gameUser);

        skins.Init(skinsListVCData);
    }
    public void OnClickCandidate()
    {
        GameDebug.LogError($"show candidates");

        var candidates = this.m_Controller.parentNav.LoadDisplay<CandidatesListViewController>();

        var candidatesListVCData = CandidatesListViewController.GetCandidatesListVCData(MGame.instance.MUser);//battleSceneController.gameUser);

        candidates.Init(candidatesListVCData);
    }  
    public void OnClickHome()
    {
        GameDebug.LogError($"show candidates");

        var candidates = this.m_Controller.parentNav.LoadDisplay<HomeViewController>();

        var candidatesListVCData = HomeViewController.GetHomeVCData(MGame.instance.MUser);//battleSceneController.gameUser);

        candidates.Init(candidatesListVCData);
    }  
    public void OnClickImprove()
    {
        GameDebug.LogError($"show improve");

        var improve = this.m_Controller.parentNav.LoadDisplay<ImproveViewController>(null,false);

        var improveVCData = ImproveViewController.GetImproveVCData(MGame.instance.MUser);//battleSceneController.gameUser);

        improve.Init(improveVCData);
    } 
    public void OnClickChat()
    {
        GameDebug.LogError($"show chat");

        var view = this.m_Controller.parentNav.LoadDisplay<ChatListViewController>();
        var viewCData = ChatListViewController.GetVCData(MGame.instance.MUser);//battleSceneController.gameUser);
        view.Init(viewCData);
    }
    #endregion


    #region Battle Events

    public void OnBattleStart()
    {
        this.ShowBattle();

        if(battleAttackBtn)
            battleAttackBtn.gameObject.SetActive(false);

#if Voodoo
        TinySauce.OnGameStarted(levelNumber: this.battleController.level.ToString());
#elif  Smillage ||GameAnalytics
        GameAnalyticsSDK.GameAnalytics.NewProgressionEvent(GameAnalyticsSDK.GAProgressionStatus.Start, this.battleController.level.ToString());
#elif Supersonic
        try
        {
            SupersonicWisdomSDK.SupersonicWisdom.Api.NotifyLevelStarted(battleController.level, null);
        }
        catch (Exception e)
        {
            GameDebug.LogException(e);
        }
#endif
        Debug.Log($"game start level:{Game.s_CurLevel}  ");
    }

    public void OnTimeOut()
    {

    }

    public void OnTriggerBoss()
    {
        battleAttackBtn.gameObject.SetActive(true);
        joyPad.gameObject.SetActive(false);
        //HidePlayerInfo(MBattleController.me);
    }

    public void AddValueToast(int value)
    {
        if (value > 0)
        {
            if (addNumToast)
            {
                addNumToast.gameObject.SetActive(true);
                addNumToast.Show(value);
            }
        }
        else
        {
            if (minusNumToast)
            {
                minusNumToast.gameObject.SetActive(true);
                minusNumToast.Show(value);
            }
        }
    }
    void BattleEnd(BattleResult battleResult)
    {
        MBattleSceneController battlescene = GetComponentInParent<MBattleSceneController>();

        DoActionDelay.DelayAction(battlescene.delayShowResultTime, () =>
        {
            battlescene.GotoResultScene(battleResult);

            Debug.Log($"Game end level:{Game.s_CurLevel}  score:{battleResult.score}");
        });
    }

    public void OnBattleEnd(BattleResult battleResult)
    {
        BattleEnd(battleResult);
		
#if Voodoo
        TinySauce.OnGameFinished(battleResult.win,battleResult.score,battleResult.level.ToString());
#elif  Smillage||GameAnalytics
        if(battleResult.win) 
            GameAnalyticsSDK.GameAnalytics.NewProgressionEvent(GameAnalyticsSDK.GAProgressionStatus.Complete,battleResult.level.ToString());
        else
            GameAnalyticsSDK.GameAnalytics.NewProgressionEvent(GameAnalyticsSDK.GAProgressionStatus.Fail,battleResult.level.ToString());
#elif Supersonic
        try
        {
            if (battleResult.win)
                SupersonicWisdomSDK.SupersonicWisdom.Api.NotifyLevelCompleted(battleResult.level, null);
            else
                SupersonicWisdomSDK.SupersonicWisdom.Api.NotifyLevelFailed(battleResult.level, null);
        }
        catch (Exception e)
        {
            GameDebug.LogException(e);
        }
#endif
    }
    #endregion


    public GameObject finger;


    protected override void Update()
    {
        base.Update();

        if (Time.frameCount % 30 == 0)
        {
            if (gameTimeText && gameTimeText.gameObject.activeInHierarchy && MBattleController)
                gameTimeText.num = MBattleController.timeLeft;
        }

#if DEBUG

        if (finger)
        {
            if (!finger.activeSelf)
                finger.SetActive(true);
                
            Vector3 screenPos = Input.mousePosition;
            finger.transform.GetComponent<RectTransform>().SetUIPosition(uiCamera.ScreenToWorldPoint(screenPos));
        }
            
        if (Input.GetMouseButton(0))
        {
            finger.transform.localScale = Vector3.Lerp(finger.transform.localScale,0.8f*Vector3.one,.4f);
        }
        else
        {
            finger.transform.localScale = Vector3.Lerp(finger.transform.localScale,1.0f*Vector3.one,.4f);
            //if (finger && finger.activeSelf)
            //    finger.SetActive(false);
        }
#endif
    }

    public void HidePlayerInfo(RoleEntity role)
    {
        this.mBattleUiWidgetInfoCtrl.HidePlayerInfo(role);
    }

    public GameObject iconPref;
    public void AddCoin(int addCoin)
    {
        DoActionDelay.DelayAction(1.6f,()=> MGame.instance.MUser.AddCoin(addCoin));
        
        for (int i = 0; i < 50; i++)
        {
            var icon = Instantiate(iconPref, transform);
            icon.transform.localPosition = Vector3.zero;
            icon.gameObject.SetActive(true);
            Vector3 centerPos = 1.5f * new Vector3(new RealRandom().Random(-100, 100), new RealRandom().Random(-100, 100), 0);
            MBattleController.TransformAnim.MoveTo(icon.transform, centerPos, .3f, () =>
            {
                DoActionDelay.DelayAction(.4f, () =>
                {
                    MBattleController.TransformAnim.MoveTo(icon.transform, coinIconPos.position, .7f, () =>
                    {
                        Destroy(icon.gameObject);
                    });
                });
            }, true);
        }
    
    }

}

public static class BattleTips
{
    public const string BattleStart = "BattleStart";
    public const string NearlyTimeOut = "NearlyTimeOut";
}